package cn.yeoman.flowcontrol.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.yeoman.flowcontrol.dal.dao.FlowTypeDAO;
import cn.yeoman.flowcontrol.dal.entity.FlowType;
import cn.yeoman.flowcontrol.service.FlowService;
import cn.yeoman.flowcontrol.service.FlowTypeService;

@Service("flowTypeService")
public class FlowTypeServiceImpl implements FlowTypeService {

	@Resource(name = "flowTypeDAO")
	private FlowTypeDAO flowTypeDAO;
	
	@Resource(name = "flowService")
	private FlowService flowService;

	@Override
	public boolean add(FlowType flowType) {
		flowType.setGmtCreate(new Date());
		return flowTypeDAO.add(flowType);
	}

	@Override
	public boolean delete(String typeCode) {
		return flowService.findCountByTypeCode(typeCode) == 0 ? flowTypeDAO.delete(typeCode) : false;
	}

	@Override
	public boolean update(FlowType flowType) {
		flowType.setGmtModified(new Date());
		return flowTypeDAO.update(flowType);
	}

	@Override
	public FlowType findFlowType(String typeCode) {
		List<FlowType> ftList = queryTypeList();
		if(ftList != null && !ftList.isEmpty()){
			for(FlowType flowType : ftList)
				if(typeCode.equals(flowType.getTypeCode()))
					return flowType;
		}
		return null;
	}
	
	@Override
	public String findTypeName(String typeCode) {
		for(FlowType flowType : queryTypeList())
			if(typeCode.equals(flowType.getTypeCode()))
				return flowType.getTypeName();
		return null;
	}
	
	@Override
	public List<FlowType> queryTypeList() {
		return flowTypeDAO.getTypeList();
	}

	@Override
	public List<FlowType> findTypeListByParams(String typeName, Character status) {
		List<FlowType> returnList = new ArrayList<FlowType>();
		List<FlowType> flowTypeList = queryTypeList();
		for(FlowType flowType : flowTypeList){
			if(StringUtils.isNotBlank(typeName) && !flowType.getTypeName().contains(StringUtils.trimToNull(typeName)))
				continue;
			if(status != null && !flowType.getStatus().equals(status))
				continue;
			returnList.add(flowType);
		}
		return returnList.isEmpty() ? null : returnList;
	}

}
